package com.wxtbk.controller;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.wxtbk.interceptor.*;
import com.wxtbk.model.WtCat;
import com.wxtbk.model.WtItem;
import com.wxtbk.model.WtUser;
import com.wxtbk.model.WtWxuser;

@Before(AuthInterceptor.class)
public class AdminController extends Controller {
	@Clear
	public void index() {
		if (!getRequest().getRequestURI().endsWith("/")) {
			redirect(getRequest().getRequestURI() + "/");
			return;
		}
		String name = getSessionAttr("nickname");
		if (name != null && !name.isEmpty()) {
			redirect("/admin/main");
			return;
		}
		render("login.jsp");
	}

	@Clear
	public void doLogin() {
		setSessionAttr("nickname", "ameizi");
		WtUser.dao.findFirst("select * from wt_user where id = 1");
		new WtUser();
		setSessionAttr("user", "ameizi");
		redirect("/admin/main");
	}

	public void main() {
		
		setAttr("itemTotalNum", WtItem.dao.GetTotalNum());
		setAttr("wxuserTotalNum", WtWxuser.dao.GetTotalNum());
		
		render("main.jsp");
	}
	
	public void dashboard(){
		render("index.jsp");
	}

	public void wxuser() {
		List<WtWxuser> users = WtWxuser.dao.getAll();
		//List<WtCat> catList = WtWxUser.dao.findAll();
		setAttr("users", users);
		render("wxuser.jsp");
	}
	
	public void cat() {
		List<WtCat> catList = WtCat.dao.findAll();
		setAttr("catlist", catList);
		render("cat.jsp");
	}
	public void doCatDel() {
		int catid = getParaToInt("catid");
		if(WtCat.dao.deleteById(catid)){
			setAttr("status",1);
		}
		renderJson();
	}
	public void doCatAdd() {
		
		String catname = getPara("catname");
		int catShowseq = getParaToInt("catseqnum");
		WtCat cat = new WtCat();
		cat.setId(cat.getNextId());
		cat.setName(catname);
		cat.setShowseq(catShowseq);
		cat.setType("custom");
		cat.save();
		setAttr("data",cat);
		setAttr("status",1);
		renderJson();
		
	}
	public void doCatSetShow() {
		String isshow = getPara("isshow");
		if (isshow.equals("Y") || isshow.equals("N")) {
			String s = getPara("catid");
			int catid = Integer.parseInt(s);
			WtCat cat = WtCat.dao.findById(catid);
			if (cat != null) {
				cat.setIsshow(isshow);
				cat.update();
			}
			renderJson();
		}
	}
	
	public void item(){

		int pageNumber = getParaToInt("pagenum");
		int pageSize = getParaToInt("pagesize");
		Page<WtItem> pageinfo = WtItem.dao.paginate(pageNumber, pageSize, "");
		setAttr("pageinfo", pageinfo);
		render("item.jsp");
	}
	
	
	
	public void doItemDel() {
		int id = getParaToInt("id");
		if(WtItem.dao.deleteById(id)){
			setAttr("status",1);
		}
		renderJson();
	}
	public void doItemSetPromt(){
		int id = getParaToInt("id");
		Boolean ispromt = getParaToBoolean("ispromt");
		if(WtItem.dao.SetPromotion(id,ispromt)){
			setAttr("status",1);
		}
		renderJson();
	}
	
	

}
